package com.lablzh.gdxy.controller;

import com.lablzh.gdxy.component.UserDetailsUtil;
import com.lablzh.gdxy.entity.Teacher;
import com.lablzh.gdxy.entity.admin.Category;
import com.lablzh.gdxy.entity.course.Course;
import com.lablzh.gdxy.entity.course.CourseApply;
import com.lablzh.gdxy.entity.course.CourseParam;
import com.lablzh.gdxy.entity.course.StudentCourse;
import com.lablzh.gdxy.entity.design.DesignApply;
import com.lablzh.gdxy.repository.admin.CategoryRepository;
import com.lablzh.gdxy.repository.course.CourseRepository;
import com.lablzh.gdxy.service.CourseService;
import com.lablzh.gdxy.service.FileService;
import com.lablzh.gdxy.service.ParametersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private CourseService courseService;
    @Autowired
    private FileService fileService;
    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private UserDetailsUtil userDetailsUtil;
    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private ParametersService parametersService;


    @PreAuthorize("hasAnyRole('teacher','admin')")
    @GetMapping("getCourseMiniCategory")
    public Map getCourseMiniType(@RequestParam("courseCategory") String courseCategory) {
        return parametersService.getCourseMiniCategory(courseCategory);
    }
    /**
     * 返回负责老师的所有课程
     *
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @GetMapping("/resTeacherCourse")
    public List<Course> resTeacherCourse() {
        String username = userDetailsUtil.getUserDetails();
        return courseRepository.findAllByTeacherUsername(username, Sort.by(Sort.Direction.DESC,"id"));
    }

    /**
     * 老师创建课程设计
     *
     * @param course
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PostMapping(value = "/team")
    public Map<String, Object> createTeam(@RequestBody Course course) throws IOException {
        course.setAudit("未审");
        Map<String, Object> map = courseService.createTeam(course);
        return map;
//        String result  = (String) map.get("result");
//        if ("添加成功！".equals(result)) {
//            Course myCourse = (Course) map.get("course");
//            Integer id = myCourse.getId();
//            fileService.summitCourseFile(request, id);
//        }
//        return result;
//        return "cao";
    }

    /**
     * 上传课程设计附件
     *
     * @param request
     * @param id
     * @return
     * @throws IOException
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PostMapping(value = "/teamSummitFile")
    public Map<String, String> createTeam(HttpServletRequest request, @RequestParam("id") Integer id) throws IOException {
        return fileService.summitCourseFile(request, id);
    }

    /**
     * 下载课设附件
     *
     * @param fileName
     * @param id
     * @param request
     * @param response
     * @throws FileNotFoundException
     */
    @GetMapping("/teamDownloadFile")
    public void teamDownloadFile(@RequestParam("fileName") String fileName,
                                 @RequestParam("id") Integer id,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws FileNotFoundException {
        fileService.downloadCourseFile(fileName, id, request, response);
    }

    /**
     * 修改课程设计
     *
     * @param course
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PutMapping("/team")
    public String updateTeam(@RequestBody Course course) {
        //course.setAudit("未审");
        return courseService.updateTeam(course);
    }

    /**
     * 获取所有课程设计
     *
     * @return
     */
    @GetMapping("/team")
    public List<Course> getAllTeam() {
        return courseService.getAllTeam();
    }

    /**
     * 条件查询课设:courseName, college, grade, major, category, teacher(出题教师)
     *
     * @return
     */
    @PreAuthorize("hasAnyRole('admin', 'teacher','student')")
    @PostMapping("/queryCourse")
    public Map getQueryAllTeacher(@RequestBody(required = false) Course course,
                                  @RequestParam(name = "page", defaultValue = "0") Integer page) {
//        System.out.println("teacher:"+teacher);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("courseName", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("college", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("grade", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("major", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("category", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("teacher", ExampleMatcher.GenericPropertyMatchers.contains());


        Example<Course> example = Example.of(course, exampleMatcher);
        Pageable designPage = PageRequest.of(page - 1, 20, Sort.by(Sort.Direction.DESC, "id"));
        Page<Course> all = courseRepository.findAll(example, designPage);
        Map<String, Object> data = new HashMap<>();
        data.put("totalPage", all.getTotalPages());
        data.put("total", all.getTotalElements());
        data.put("course", all.getContent());
        return data;
    }

    /**
     * 根据id获取课程设计
     *
     * @param id
     * @return
     */
    @GetMapping("/teamById")
    public Course getTeamById(@RequestParam("ID") Integer id) {
        return courseService.getTeamById(id);
    }

    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PostMapping("/teamParameter")
    public String updateTeamParameter(@RequestBody CourseParam courseParam) {
        return courseService.updateTeamParameter(courseParam);
    }

    @GetMapping("/teamStudent")
    public List<Course> getTeamStudent() {
        return courseService.getTeamStudent();
    }

    @PreAuthorize("hasAnyRole('teacher','admin')")
    @DeleteMapping("/team")
    public String deleteTeam(@RequestParam("ID") Integer id) {
        return courseService.deleteTeam(id);
    }

    /**
     * 学生选择课程设计
     *
     * @param id
     * @return
     */
    @PostMapping("/studentCourse")
    public String chooseCourse(@RequestParam("ID") Integer id) {
        return courseService.chooseCourse(id);
    }

    /**
     * 负责老师获取课程设计
     *
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @GetMapping("/courseTeacher")
    public List<Course> getCourseTeacher() {
        return courseService.getCourseTeacher();
    }

    //老师获取自己负责的课程设计栏目
    @GetMapping("/courseParameter")
    public List<Category> courseParameter() {
        String username = userDetailsUtil.getUserDetails();
        return categoryRepository.findAllByCourseTeacherName(username,Sort.by(Sort.Direction.DESC,"id"));
    }

    /**
     * 退选
     *
     * @param id
     * @return
     */
    @DeleteMapping("/studentCourse")
    public String deleteCourse(@RequestParam("ID") Integer id) {

        return courseService.deleteCouse(id);
    }

    /**
     * 学生获取自己选择的课程设计
     *
     * @return
     */
    @GetMapping("/courseStudent")
    public List<StudentCourse> getCourseStudent() {
        return courseService.getCourseStudent();
    }

    /**
     * 学生获取自己申请过的课程设计
     * @param
     * @return
     */
    @GetMapping("/courseStudentApply")
    public List<CourseApply> getCourseStudentApply() {
        return courseService.getCourseStudentApply();
    }

    @PostMapping("/apply")
    public String apply(@RequestParam("ID") Integer id) {
        return courseService.apply(id);
    }

    /**
     * 直接删除学生
     * @param id
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher', 'admin')")
    @DeleteMapping("/deleteStudent")
    public String deleteStudent(@RequestParam("id") Integer id) {
        return courseService.deleteStudent(id);
    }

    /**
     * 撤销申请
     *
     * @param id
     * @return
     */
    @DeleteMapping("/undo")
    public String undo(@RequestParam("ID") Integer id) {
        return courseService.undo(id);
    }

    @PreAuthorize("hasAnyRole('teacher','admin')")
    @GetMapping("/applyTeacher")
    public List<CourseApply> applyTeacher(@RequestParam("ID") Integer id) {
        return courseService.applyTeacher(id);
    }

    /**
     * 学生查看自己的申请
     *
     * @return
     */
    @GetMapping("/applyStudent")
    public List<CourseApply> applyStudent() {
        return courseService.applyStudent();
    }

    /**
     * 审核通过
     *
     * @param id
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PutMapping("/confirm")
    public String confirm(@RequestParam("ID") Integer id) {
        return courseService.confirm(id);
    }

    /**
     * 退回重选
     *
     * @param id
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PutMapping("/refuse")
    public String refuse(@RequestParam("ID") Integer id) {
        return courseService.refuse(id);
    }

    /**
     * 获取某课设所有学生
     *
     * @param id
     * @return
     */
    @GetMapping("/studentsChoosed")
    public List<StudentCourse> getChoosed(@RequestParam("ID") Integer id) {
        return courseService.getChoosed(id);
    }

    /**
     * 获取已提交和未提交的学生
     *
     * @param summit
     * @param id
     * @return
     */

    @PreAuthorize("hasAnyRole('teacher','admin')")
    @GetMapping("/studentBySummit")
    public List<StudentCourse> getStudentBySummit(@RequestParam("summit") String summit,
                                                  @RequestParam("ID") Integer id) {
        return courseService.getStudentBySummit(summit, id);
    }

    /**
     * 获取已批阅和为批阅的学生
     *
     * @param id
     * @param review
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @GetMapping("/studentByReview")
    public List<StudentCourse> getStudentByReview(@RequestParam("ID") Integer id,
                                                  @RequestParam("review") String review) {
        return courseService.getStudentByReview(review, id);
    }

    /**
     * 上传课程设计报告
     *
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadReport")
    public Map<String, String> uploadReport(HttpServletRequest request) throws IOException {
        String category = request.getParameter("category");
        Integer id = Integer.valueOf(request.getParameter("ID"));//学生课程表id
        return courseService.uploadReport(request, category, id);
    }

    /**
     * 批阅课程设计
     *
     * @param id
     * @param studentUsername
     * @param score
     * @param level
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PutMapping("/review")
    public String review(
            @RequestParam("courseID") Integer id,
            @RequestParam("studentUsername") String studentUsername,
            @RequestParam("score") Integer score,
            @RequestParam("level") String level,
            @RequestParam("note") String note) {
        return courseService.review(id, studentUsername, score, level, note);
    }

    /**
     * 查询课程设计成绩
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher', 'admin')")
    @PostMapping("/queryPerformance")
    public Map<String, Object> export(@RequestBody StudentCourse studentCourse,@RequestParam("page")int page) {

        return courseService.queryPerformance(studentCourse,page);
    }

    /**
     * 下载课程设计成绩报表
     * @param request
     * @param response
     * @return
     * @throws FileNotFoundException
     */
    @PreAuthorize("hasAnyRole('teacher', 'admin')")
    @PostMapping("/downloadExcel")
    public void downloadExcel(@RequestBody StudentCourse studentCourse,
                              @RequestParam("sort") String sort,
                              HttpServletRequest request,
                              HttpServletResponse response
    ) throws FileNotFoundException {
        courseService.downloadExcel(studentCourse, sort, request, response);
    }
}
